uniform sampler2D texture, texture2, texture3;
uniform float state;



bool checkGreen(vec4 color) {
	
	//Calulate "distance" from green (0.0, 1.0, 0.0)
	//to current color.
	float green_dist = sqrt((color.r*color.r)+
				(color.g-1.0)*(color.g-1.0)+
				(color.b*color.b));
	//Max distance to green.
	float green_tolerance = 0.81;

	if ((color.g/color.r > 1.1 && color.g/color.b > 1.1) && color.g > 0.2) {
		return true;
	}
	else {
		return false;
	}
}
void main()
{
	//Texture with green-screen.
	vec4 tex = texture2D(texture, gl_TexCoord[0].xy); 
	//Background texture.	
	vec4 tex2 = texture2D(texture2, gl_TexCoord[0].xy); 
	vec4 tex3 = texture2D(texture3, gl_TexCoord[0].xy); 

	vec4 final_color = vec4(0.0, 0.0, 0.0, 0.0);

		//FUNGERANDE GREEN-SCREEN FILTER

	//If the current color i within the radius of green_tolerance,
	//replace the pixel with the corresponding one from background texture.
	if (checkGreen(tex)) {
		final_color = tex2;
	}
	//Else, keep current color from the green-screen texture.
	else {
		float offset = 1.0/800.0;
		vec2 xy = gl_TexCoord[0].xy;
		vec4 upper_left = texture2D(texture, vec2(xy.x-offset, xy.y+offset)); 
		vec4 upper = texture2D(texture, vec2(xy.x, xy.y+offset));
		vec4 upper_right = texture2D(texture, vec2(xy.x+offset, xy.y+offset));
		vec4 left = texture2D(texture, vec2(xy.x-offset, xy.y));
		vec4 right = texture2D(texture, vec2(xy.x+offset, xy.y));
		vec4 lower_left = texture2D(texture, vec2(xy.x-offset, xy.y-offset)); 
		vec4 lower = texture2D(texture, vec2(xy.x, xy.y-offset));
		vec4 lower_right = texture2D(texture, vec2(xy.x+offset, xy.y-offset));
		if (checkGreen(upper_left)) {
			final_color = vec4(1.0,0.0,0.0,1.0);
		}
		else if (checkGreen(upper)) {
			final_color = vec4(1.0,0.0,0.0,1.0);
		}
		else if (checkGreen(upper_right)) {
			final_color = vec4(1.0,0.0,0.0,1.0);
		}
		else if (checkGreen(lower_left)) {
			final_color = vec4(1.0,0.0,0.0,1.0);
		}
		else if (checkGreen(lower)) {
			final_color = vec4(1.0,0.0,0.0,1.0);
		}
		else if (checkGreen(lower_right)) {
			final_color = vec4(1.0,0.0,0.0,1.0);
		}
		else if (checkGreen(left)) {
			final_color = vec4(1.0,0.0,0.0,1.0);
		}
		else if (checkGreen(right)) {
			final_color = vec4(1.0,0.0,0.0,1.0);
		}
		else {
			final_color = tex;
		}	
		
	}

	gl_FragColor = final_color;

}
